package cn.dglydrpy.study.j2ee.servlet.day09;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CommentFilter implements Filter{//1.实现javax.servlet.Filter接口
	private List<String> fstrings = new ArrayList<String>();

	//2.实例化
	public CommentFilter() {//容器启动之后，会立即将过滤器实例化（只会创建一个实例）
		System.out.println("1.commentFilter的构造器");
	}
	//3.初始化
	public void init(FilterConfig arg0) throws ServletException{
		/*
		 * 实例化之后，容器立即调用init()来初始化
		 * 容器会将FilterConfig对象作为参数传递
		 * FilterConfig对象提供了读取初始化参数的方法
		 * init(）也只执行1次
		 */
		System.out.println("2.commentFilter的初始化");
		System.out.println(arg0);
		String[] zds = arg0.getInitParameter("过滤字段").split(",");
		for (String zd : zds) {
			fstrings.add(zd);
		}

	}
	//4.调用
	public void doFilter(ServletRequest sRequest, ServletResponse sResponse,FilterChain chain) throws IOException, ServletException {//处理过滤请求
		/*
		 * 1.容器会将request和response传递过来
		 * 2.ServletRequest是HttpServletRequest的父接口  ServletResponse是HttpServletResponse的父接口 过渡设计的产物,我们需要强制转换
		 * 3.如果调用了过滤器链的doFilter（）,则容器会继续向后调用，否则中断请求，返回处理结果
		 */
		HttpServletRequest request = (HttpServletRequest) sRequest;
		HttpServletResponse response = (HttpServletResponse) sResponse;

		request.setCharacterEncoding("utf-8");
		String content = request.getParameter("content");
		for (String string : fstrings) {
			if(content.contains(string)){//indexOf(string) != -1
				//包含敏感字
				request.setAttribute("msg", "请文明发言");
				request.getRequestDispatcher("comment.jsp").forward(request, response);
				return;
			}
		}
		//继续向后调用
		try {
			System.out.println("通过过滤器commentFilter");
			System.out.println("3.commentFilter的doFilter()执行完毕！");
			chain.doFilter(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	//5.销毁
	public void destroy(){//容器删除过滤器之前，会调用destroy（） 也只执行1次
		System.out.println("4.commentFilter的销毁");
	}
}
